//-----------------------------------------------------------------------

// <copyright file="FloatFieldDefinition.cs" company="Jamie Knight">

// Copyright (c) Jamie Knight. All rights reserved.

// </copyright>

//-----------------------------------------------------------------------

using System;
using System.Windows.Controls;
using System.Windows.Data;

namespace DevKnightlie.WPF.AutoForm.FieldDefinitions
{
    /// <summary>
    /// Validation rule which checks that input is a valid floating-point number
    /// </summary>
    public class FloatValidationRule : ValidationRule
    {

        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            bool isValid = false;
            float f = 0;
            isValid = float.TryParse(value as String, out f);
            return new ValidationResult(isValid, null);
        }
    }


    /// <summary>
    /// Field definition which creates a TextBox whose input must be a valid floating-point number
    /// </summary>
    public class FloatFieldDefinition: BaseFieldDefinition
    {

        #region Methods

        public override void BuildInputControl()
        {
            TextBox floatTextBox = new TextBox()
            {
                TextAlignment = System.Windows.TextAlignment.Right
            };
            Binding floatBinding = new Binding(PropertyName);
            floatBinding.ValidationRules.Add(new FloatValidationRule());
            BindingOperations.SetBinding(floatTextBox, TextBox.TextProperty, floatBinding);
            SetupEnabledBinding(floatTextBox);
            ContainerControl = InputControl = floatTextBox;
        }
        
        #endregion

    }
}
